package server;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

public class Question {
	
	private String question;
	private char correctAnswerChar;
	private String[] answers;
	private char[] answerTokens;
	private Date time;
	
	/**
	 * Initialize the question.
	 * @param question the question that should be asked.
	 * @param answersArray array of possible answers. The first char of each String is used as a unique token.
	 * @param correctAnswer the correct answer.
	 */
	public Question(String question, String[] answersArray, String correctAnswer) {
		this.question = question != null ? question : new String();
		
		if (answersArray != null){
			answers = answersArray;
		} else {
			String[] dummy = {" "};
			answers = dummy;
		}
		
		answerTokens = new char[answers.length];
		
		/* 
		 * Strip the answer tokens from the answers. The tokens will keep their position
		 */
		for ( int i = 0; i<answers.length; i++ ){
			answerTokens[i] = answers[i].charAt(0);
			
			answers[i] = answers[i].substring(1, answers[i].length()); // Remove the first char
		}
		
		/*
		 * Now shuffle the answers
		 */
		ArrayList<String> a = new ArrayList<String>();
		
		for (int i = 0; i<answers.length; i++)
			a.add(answers[i]);
		
		Collections.shuffle(a);
		
		answers = (String[]) a.toArray(answers);
		
		/*
		 * Find the position of the correct answer and copy the answer token.
		 */
		for (int i = 0; i < answers.length; i++){
			if (answers[i].endsWith(correctAnswer)){
				correctAnswerChar = answerTokens[i];
				break;
			}
		}
		
		// time should not be null after construction.
		time = new Date();
	}
	
	/**
	 * Returns question and possible answers. Registers the time this method was called.
	 * @return question and possible answers.
	 */
	public String getQuestion() {
		String r = new String();
		
		r += question + "\n";
		
		for (int i = 0; i < answers.length; i++)
			r += answerTokens[i] + answers[i] + "\n";

		time = new Date(); // This is returned when the question is posted. 
		return r;
	}
	
	public long getTime(){
		return time.getTime();
	}
	
	/**
	 * Validates a answer.
	 * @param ans answer string from a player. Only the first char is looked at.
	 * @return true if answer is correct, false otherwise.
	 */
	public boolean validateAnswer(Answer ans) {
		return ans.getAnswer().charAt(0) == correctAnswerChar;
	}
	
}
